/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultarTime.java
 *
 * Created on 02/05/2011, 00:40:33
 */
package Interface;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import ludi.Curso;
import ludi.Modalidade;
import ludi.Time;
import ludi.Usuario;
import utils.BancoDeDados;

/**
 *
 * @author alison
 */
public class ConsultarTime extends javax.swing.JInternalFrame {

    BancoDeDados banco;
    Usuario usuario;
    ArrayList<String> listaDeCursos;

    /** Creates new form ConsultarTime */
    public ConsultarTime(BancoDeDados banco, Usuario usuario) {
        try {
            this.banco = banco;
            this.usuario = usuario;
            this.listaDeCursos = banco.getListaDeCursos();
            initComponents();
            if (usuario.getPermissoes() == 2){
                seletorCurso.setSelectedIndex(listaDeCursos.indexOf(usuario.getLogin()) + 1);
                seletorCurso.setEnabled(false);
            }
            updateTabelaTimes();
            setVisible(true);
        } catch (SQLException ex) {
            Logger.getLogger(ConsultarTime.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollTabelaTimes = new javax.swing.JScrollPane();
        tabelaTimes = new javax.swing.JTable();
        botaoGerenciar = new javax.swing.JButton();
        botaoCancelar = new javax.swing.JButton();
        seletorCurso = new javax.swing.JComboBox();
        labelSelecioneCurso = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setTitle("Consultar Times");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameActivated(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        tabelaTimes.setAutoCreateRowSorter(true);
        tabelaTimes.setBackground(new java.awt.Color(254, 254, 254));
        ArrayList<Integer> listaDeTimes;
        try{
            listaDeTimes = banco.getListaDeTimes(null, null);
        } catch (SQLException ex) {
            listaDeTimes = null;
        }
        tabelaTimes.setModel(modeloTabelaTimes(listaDeTimes));
        tabelaTimes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        scrollTabelaTimes.setViewportView(tabelaTimes);

        botaoGerenciar.setText("Gerenciar Time Selecionado");
        botaoGerenciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoGerenciarActionPerformed(evt);
            }
        });

        botaoCancelar.setText("Cancelar");
        botaoCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarActionPerformed(evt);
            }
        });

        ArrayList<String> nomesDosCursos = new ArrayList<String>(0);

        nomesDosCursos.add("Todos");

        for (int i = 0; i < listaDeCursos.size(); i++){
            try {
                Curso curso = banco.getCurso(listaDeCursos.get(i));
                nomesDosCursos.add(curso.getNome() + " - " + curso.getLogin());
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        seletorCurso.setModel(new javax.swing.DefaultComboBoxModel(nomesDosCursos.toArray()));
        seletorCurso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                seletorCursoActionPerformed(evt);
            }
        });

        labelSelecioneCurso.setText("Selecione um curso:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(seletorCurso, javax.swing.GroupLayout.Alignment.LEADING, 0, 356, Short.MAX_VALUE)
                    .addComponent(scrollTabelaTimes, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelSelecioneCurso)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(botaoCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                        .addComponent(botaoGerenciar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelSelecioneCurso)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(seletorCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrollTabelaTimes, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoGerenciar)
                    .addComponent(botaoCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_botaoCancelarActionPerformed

    private void seletorCursoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seletorCursoActionPerformed
        updateTabelaTimes();
    }//GEN-LAST:event_seletorCursoActionPerformed

    private void botaoGerenciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoGerenciarActionPerformed
        if (tabelaTimes.getSelectedRow() < 0){
            JOptionPane.showMessageDialog(this, "Selecione um time!", "Consultar Times", JOptionPane.INFORMATION_MESSAGE);
        } else {
            String coluna;
            int i = -1;
            do {
                i++;
                coluna = tabelaTimes.getColumnName(i);
            } while (!(coluna.equals("ID")));

           CriarTime frame;
            try {
                frame = new CriarTime(banco, usuario, banco.getTime((Integer) tabelaTimes.getValueAt(tabelaTimes.getSelectedRow(), i)));
                frame.setVisible(true);
                this.getDesktopPane().add(frame);
                try {
                    frame.setSelected(true);
                } catch (java.beans.PropertyVetoException e) {}
            } catch (SQLException ex) {
                Logger.getLogger(ConsultarUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_botaoGerenciarActionPerformed

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameActivated
        updateTabelaTimes();
    }//GEN-LAST:event_formInternalFrameActivated

    private DefaultTableModel modeloTabelaTimes(ArrayList<Integer> listaDeTimes){
        String[][] dados = new String [0][];
        String[] colunas = new String [] {"ID", "Modalidade", "Gênero", "Curso"};

        DefaultTableModel modelo = new DefaultTableModel(dados, colunas){
             Class[] types = new Class [] {
                 java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
             };
             boolean[] canEdit = new boolean [] {
                 false, false, false, false
             };

             @Override
             public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
             }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };
        
        for (int i = 0; i < listaDeTimes.size(); i++){
            try {
                Time time = banco.getTime(listaDeTimes.get(i));
                Modalidade modalidade = banco.getModalidade(time.getIdModalidade());
                String genero = (modalidade.getGenero() == 1)? "Masculino" : "Feminino";
                
                modelo.addRow(new Object [] {time.getId(), modalidade.getNome(), genero, time.getCurso()});
            } catch (SQLException ex) {
                Logger.getLogger(ConsultarTime.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return modelo;
    }

    private void updateTabelaTimes(){
        ArrayList<Integer> listaDeTimes;
        try {
            if (seletorCurso.getSelectedIndex() == 0){
                listaDeTimes = banco.getListaDeTimes(null, null);
            } else {
                listaDeTimes = banco.getListaDeTimes(listaDeCursos.get(seletorCurso.getSelectedIndex() - 1), "curso");
            }
        } catch (SQLException e) {
            listaDeTimes = new ArrayList<Integer>(0);
        }
        tabelaTimes.setModel(modeloTabelaTimes(listaDeTimes));

        tabelaTimes.getColumnModel().getColumn(0).setMinWidth(40);
        tabelaTimes.getColumnModel().getColumn(0).setMaxWidth(40);
        tabelaTimes.getColumnModel().getColumn(1).setMinWidth(150);
        tabelaTimes.getColumnModel().getColumn(2).setMinWidth(100);
        tabelaTimes.getColumnModel().getColumn(2).setMaxWidth(100);
        tabelaTimes.getColumnModel().getColumn(3).setMinWidth(60);
        tabelaTimes.getColumnModel().getColumn(3).setMaxWidth(60);
        tabelaTimes.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoCancelar;
    private javax.swing.JButton botaoGerenciar;
    private javax.swing.JLabel labelSelecioneCurso;
    private javax.swing.JScrollPane scrollTabelaTimes;
    private javax.swing.JComboBox seletorCurso;
    private javax.swing.JTable tabelaTimes;
    // End of variables declaration//GEN-END:variables
}
